import { GetServerSidePropsContext } from "next";
import styles from "@/styles/Question.module.scss";
import PageWrapper from "@/components/PageWrapper";
import { getQuestionById } from "@/services/question";
import { getComponent } from "@/components/QuestionComponents";

type ComponentBase = {
  fe_id: string;
  type: string;
  title: string;
  isHidden: boolean;
};

// 定义各种组件props类型
type InputComponentProps = {
  title: string;
  placeholder: string;
};

type RadioComponentProps = {
  title: string;
  options: Array<{ text: string; value: string }>;
  value: string;
  isVertical: boolean;
};

// 定义具体组件类型
type InputComponent = ComponentBase & {
  props: InputComponentProps;
};

type RadioComponent = ComponentBase & {
  props: RadioComponentProps;
};

// 组件列表项的联合类型
type ComponentItem = InputComponent | RadioComponent;

type PropsType = {
  code: number;
  data?: {
    id: string;
    title: string;
    desc?: string;
    js?: string;
    css?: string;
    isDeleted: boolean;
    isPublished: boolean;
    componentList: Array<ComponentItem>;
  };
};

export default function Question(props: PropsType) {
  const { code, data } = props;
  const {
    id,
    title = "",
    desc,
    isDeleted,
    isPublished,
    componentList = [],
  } = data || {};
  if (code !== 200) {
    return (
      <PageWrapper title="错误">
        <h1>错误</h1>
        <p>数据错误</p>
      </PageWrapper>
    );
  }

  if (isDeleted) {
    return (
      <PageWrapper title={title} desc={desc}>
        <h1>{title}</h1>
        <p>该问卷已经被删除</p>
      </PageWrapper>
    );
  }

  if (!isPublished) {
    return (
      <PageWrapper title={title} desc={desc}>
        <h1>{title}</h1>
        <p>该问卷尚未发布</p>
      </PageWrapper>
    );
  }

  const ComponentListElem = (
    <>
      {componentList.map((c) => {
        const ComponentElem = getComponent(c);
        return (
          <div key={c.fe_id} className={styles.componentWrapper}>
            {ComponentElem}
          </div>
        );
      })}
    </>
  );

  return (
    <>
      <PageWrapper title={title}>
        <form action={`/api/answer`} method="POST">
          <input name="questionId" value={id} type="hidden" />
          {ComponentListElem}
          <div className={styles.submitBtnContainer}>
            <button type="submit">提交</button>
          </div>
        </form>
      </PageWrapper>
    </>
  );
}

export async function getServerSideProps(context: GetServerSidePropsContext) {
  const { id } = context.params || {};
  // 确保 id 是字符串类型
  if (!id || Array.isArray(id)) {
    return {
      props: {
        code: -1,
        data: null,
      },
    };
  }

  const question = await getQuestionById(id);
  return {
    props: { ...question },
  };
}
